package selef.xiafan.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import selef.xiafan.dao.CategoryDao;
import selef.xiafan.entity.system.Category;
import selef.xiafan.query.CategoryQuery;
import selef.xiafan.service.ICategoryService;
import selef.xiafan.util.result.PageResult;

import java.util.List;

@Service
public class ICategoryServiceImpl implements ICategoryService {
    @Autowired
    CategoryDao categoryDao;

    /*
     * 查询所有如果使用new Sort，会提示new Sort已经被私有化，无法使用new Sort(Sort.Direction.DESC,properties)
     * */
    @Override
    public List<Category> getAll() {
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        return categoryDao.findAll(sort);
    }

    @Override
    public PageResult queryPage(CategoryQuery categoryQuery) {
        Integer page = (categoryQuery.getPage() - 1) * categoryQuery.getSize();
        Integer size = categoryQuery.getSize();
        String categoryQueryName = categoryQuery.getName();


        // 刷新页面或者不带参数查询时
        if (categoryQueryName == "" || categoryQueryName == null) {
            Long total = categoryDao.countAll(); // 查询总数
            if (total == 0L) {
                return new PageResult<>();
            }
            List<Category> categoryList = categoryDao.findAllNoQuery(page, size);
            return new PageResult<>(total, categoryList);
            // 查询携带名字时
        } else {
            Long total = categoryDao.countAllByQuery(categoryQueryName);
            List<Category> categoryList = categoryDao.findAllByQuery(page, size, categoryQueryName);
            return new PageResult<>(total, categoryList);
        }

    }

    @Override
    public Integer AddOrUpdate(Category category) {
        if (category.getId() == null) {
            categoryDao.save(category);
            return 1; // 添加成功
        } else {
            Category categoryForDb = new Category();
            categoryForDb.setDescription(category.getDescription());
            categoryForDb.setId(category.getId());
            categoryForDb.setName(category.getName());
            categoryDao.save(categoryForDb);
            return 2; // 修改成功
        }
    }

    @Override
    @Transactional
    public Integer deleteOne(Category category) {
        categoryDao.delete(category);
        return 1;
    }

}
